package com.appleyk.spring.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * <p>越努力，越幸运</p>
 * 安全认证配置类，需要加载到Spring容器中
 *
 * @author appleyk
 * @version V.0.1.1
 * @blob https://blog.csdn.net/appleyk
 * @date created on  8:21 下午 2021/1/4
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    // 1、添加自定义用户
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password("admin123").roles("super-admin").authorities("p1,p2")
                .and()
                .withUser("appleyk").password("123456a").roles("admin").authorities("p2");
    }

    // 2、密码编码器（用户输入的密码要和security的密码进行比对，所以编码器要统一）
    @Bean
    public PasswordEncoder passwordEncoder() {
        // 不需要对密码进行加密，直接用字符串来比较
        return NoOpPasswordEncoder.getInstance();
    }

    // 3、安全拦截机制
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 配置认证请求
        http.authorizeRequests()
                .antMatchers("/auth/r/r1").hasAuthority("p1")
                .antMatchers("/auth/r/r2").hasAuthority("p2")
                // 所有/auth/**路径请求必须完成认证通过才可以访问
                .antMatchers("/auth/**").authenticated()
                // 除此之外的任何请求全部放行
                .anyRequest().permitAll()
                // 登录方式，表单登录
                .and().formLogin()
                .loginPage("/login-view") // 登录页面
                .loginProcessingUrl("/login")//登录处理的页面是login
                // 登录成功后，指向下面这个地址
                .successForwardUrl("/auth/login-success")
                .failureForwardUrl("/auth/login-fail");
        http.csrf().disable();
    }
}
